﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using AppCash;
using DevComponents.DotNetBar;
using Maticsoft.Common;
using Model;
using Newtonsoft.Json;

namespace AppCash
{
    public partial class frmMain : Form
    {
        private Thread _LoadThread;
        bool start = true;
        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            start = false;
            Application.Exit();
        }

        /// <summary>
        /// 检测要打开的tab
        /// </summary>
        /// <param name="tabName"></param>
        /// <returns></returns>
        private bool IsOpenTab(string tabName)
        {
            bool isOpened = false;

            foreach (TabItem tab in tabMain.Tabs)
            {
                if (tab.Name == tabName.Trim())
                {
                    isOpened = true;
                    tabMain.SelectedTab = tab;
                    break;
                }
            }
            return isOpened;
        }
        public void openWindow(Form frm, string Name)
        {
            DevComponents.DotNetBar.TabItem tp = new DevComponents.DotNetBar.TabItem();
            DevComponents.DotNetBar.TabControlPanel tcp = new DevComponents.DotNetBar.TabControlPanel();
            tp.MouseDown += new MouseEventHandler(tp_MouseDown);
            tcp.Dock = System.Windows.Forms.DockStyle.Fill;
            tcp.Location = new System.Drawing.Point(0, 0);

            frm.TopLevel = false;
            frm.Dock = System.Windows.Forms.DockStyle.Fill;
            frm.FormBorderStyle = FormBorderStyle.None;
            frm.Show();
            tcp.Controls.Add(frm);
            tp.Text = frm.Text;
            tp.Name = Name;

            if (!IsOpenTab(Name))
            {
                tcp.TabItem = tp;
                tp.AttachedControl = tcp;
                tabMain.Controls.Add(tcp);
                tabMain.Tabs.Add(tp);
                tabMain.SelectedTab = tp;
            }
            tabMain.Refresh();
        }
        private void tp_MouseDown(object sender, MouseEventArgs e)
        {
            tabMain.SelectedTab = (TabItem)sender;
            if (e.Button == MouseButtons.Right && tabMain.SelectedTab != null)
            {
                this.tabMain.Select();
                cms.Show(this.tabMain, e.X, e.Y);
            }
        }

        private void tabMain_TabItemClose(object sender, TabStripActionEventArgs e)
        {
            TabItem tb = tabMain.SelectedTab;
            tabMain.Tabs.Remove(tb);
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.Text = this.Text + " --【" + ZhiKeDuoServer.Model.GlobalsInfo.Shop.Name + "】";
            lblDate.Text = DateTime.Now.Date.ToString("yyyy年MM月dd日");
            lblShopName.Text = ZhiKeDuoServer.Model.GlobalsInfo.Shop.Name;
            lblUser.Text = ZhiKeDuoServer.Model.GlobalsInfo.UserName;
            lblAddr.Text = ZhiKeDuoServer.Model.GlobalsInfo.Shop.Addr;

            var AllRpis = new List<PriRole>();
            foreach (RibbonTabItem item in ribbonControl1.Items)
            {
                PriRole pr = new PriRole();
                pr.Name = item.Text;
                foreach (RibbonBar Bar in item.Panel.Controls)
                {
                    foreach (ButtonItem button in Bar.Items)
                    {

                        pr.Subs.Add(new PriRole { Name = button.Text });
                    }
                }
                AllRpis.Add(pr);


            }
            AllRpi.Pris = AllRpis;
            foreach (var pitem in ZhiKeDuoServer.Model.GlobalsInfo.Pris)
            {

                foreach (RibbonTabItem item in ribbonControl1.Items)
                {

                    if (item.Text == pitem.Name)
                    {
                        if (pitem.sel)
                        {

                            foreach (RibbonBar Bar in item.Panel.Controls)
                            {
                                foreach (ButtonItem button in Bar.Items)
                                {

                                    foreach (var psubitem in pitem.Subs)
                                    {

                                        if (button.Text == psubitem.Name)
                                        {
                                            button.Visible = psubitem.sel;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            item.Visible = false;
                        }
                    }

                }
            }
            startserver();
        }


        private void btnShop_Click(object sender, EventArgs e)
        {
            //弹出商铺信息窗口
            frmShop frm = new frmShop();
            openWindow(frm, frm.Name);
        }
        private void btnSys_Click(object sender, EventArgs e)
        {
            frmCashSet frm = new frmCashSet();

            openWindow(frm, frm.Name);
        }
        private void btnHotKey_Click(object sender, EventArgs e)
        {
            frmHotKey frm = new frmHotKey();
            openWindow(frm, frm.Name);
        }

        private void btnVip_Click(object sender, EventArgs e)
        {
            frmVip frm = new frmVip();
            openWindow(frm, frm.Name);
        }

        private void btnUsers_Click(object sender, EventArgs e)
        {
            frmUsers frm = new frmUsers();
            openWindow(frm, frm.Name);
        }

        private void btnSupp_Click(object sender, EventArgs e)
        {
            frmSup frm = new frmSup();
            openWindow(frm, frm.Name);
        }

        private void btnGoods_Click(object sender, EventArgs e)
        {
            frmGoods frm = new frmGoods();
            openWindow(frm, frm.Name);
        }

        private void btnCategory_Click(object sender, EventArgs e)
        {
            frmCategory frm = new frmCategory();
            openWindow(frm, frm.Name);
        }

        private void btnUnit_Click(object sender, EventArgs e)
        {
            frmUnit frm = new frmUnit();
            openWindow(frm, frm.Name);
        }

        private void btnInput_Click(object sender, EventArgs e)
        {
            frmInput frm = new frmInput();
            openWindow(frm, frm.Name);
        }

        private void btnPD_Click(object sender, EventArgs e)
        {
            frmPD frm = new frmPD();
            openWindow(frm, frm.Name);
        }

        private void btnGoodsSearch_Click(object sender, EventArgs e)
        {
            frmGoodsSearch frm = new frmGoodsSearch();
            openWindow(frm, frm.Name);
        }

        private void btnCash_Click(object sender, EventArgs e)
        {
            frmCash frm = new frmCash();
            //openWindow(frm, frm.Name);
            frm.Show();
        }

        private void btnReport1_Click(object sender, EventArgs e)
        {
            frmReport1 frm = new frmReport1();
            openWindow(frm, frm.Name);
        }

        private void btnJB_Click(object sender, EventArgs e)
        {
            frmJB frm = new frmJB();
            openWindow(frm, frm.Name);
        }

        private void btnReportToDay_Click(object sender, EventArgs e)
        {
            frmToday frm = new frmToday();
            openWindow(frm, frm.Name);
        }

        private void btnReportDay_Click(object sender, EventArgs e)
        {
            frmReportDay frm = new frmReportDay();
            openWindow(frm, frm.Name);
        }

        private void btnReportMonth_Click(object sender, EventArgs e)
        {
            frmReportMonth frm = new frmReportMonth();
            openWindow(frm, frm.Name);
        }

        private void tabMain_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && tabMain.SelectedTab != null)
            {
                this.tabMain.Select();
                cms.Show(this.tabMain, e.X, e.Y);
            }
        }

        private void tabMain_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && tabMain.SelectedTab != null)
            {
                this.tabMain.Select();
                cms.Show(this.tabMain, e.X, e.Y);
            }
        }

        private void btnMCloseAll_Click(object sender, EventArgs e)
        {
            tabMain.Tabs.Clear();
        }

        private void btnMCloseOther_Click(object sender, EventArgs e)
        {

            do
            {
                if (tabMain.SelectedTab != tabMain.Tabs[0])
                {
                    tabMain.Tabs.RemoveAt(0);
                }
                else
                {
                    tabMain.Tabs.RemoveAt(1);
                }

            } while (tabMain.Tabs.Count != 1);

            tabMain.Refresh();
        }

        private void buttonItem2_Click(object sender, EventArgs e)
        {
            var frm = new frmrole();
            openWindow(frm, frm.Name);
        }

        private void buttonItem6_Click(object sender, EventArgs e)
        {

            var frm = new frmCashSet();
            openWindow(frm, frm.Name);
        }

        private void buttonItem1_Click(object sender, EventArgs e)
        {
            MessageBoxEx.Show("知客多!");
        }

        /// <summary>
        /// 检测待同步请求，并放入队列
        /// </summary>
        private void DetectionPrintRequest()
        {

            string baseadd = "http://hat.ohthink.com/";
            try
            {
                string json = System.IO.File.ReadAllText(System.Environment.CurrentDirectory + "/serverconfig");
                var rlt = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
                baseadd = rlt["serveraddr"];
            }
            catch (Exception ex)
            {

            }
            string api = baseadd + "/sycapi/sync/";

            JsonSerializerSettings setting = new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                Formatting = Formatting.None
            };
            ZhiKeDuoServer.BLL.ShopInfo bShop = new ZhiKeDuoServer.BLL.ShopInfo();
            ZhiKeDuoServer.Model.ShopInfo mShop = new ZhiKeDuoServer.Model.ShopInfo();
            mShop = bShop.GetModel(1);
            while (start)
            {

                try
                {

                    // 同步会员
                    WebClient wc = new WebClient();
                    #region ------上传同步------
                    ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.MemberInfo> bmem = new ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.MemberInfo>();
                    List<ZhiKeDuoServer.Model.MemberInfo> lsmem = bmem.GetList("syc=0");
                    foreach (ZhiKeDuoServer.Model.MemberInfo item in lsmem)
                    {
                        string json = JsonConvert.SerializeObject(item);
                        wc.PostJson(api + "add/memberinfo/" + mShop.Shop, json);
                        item.syc = 1;
                        bmem.Update(item);
                    }
                    /// 同步订单
                    /// 
                    /// 
                    ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.SaleInfo> bSaleInfo = new ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.SaleInfo>();
                    List<ZhiKeDuoServer.Model.SaleInfo> lsSaleInfo = bSaleInfo.GetList("syc=0");



                    foreach (ZhiKeDuoServer.Model.SaleInfo item in lsSaleInfo)
                    {
                        string json = JsonConvert.SerializeObject(item, setting);
                        wc.PostJson(api + "add/saleinfo/" + mShop.Shop, json);
                        item.syc = 1;
                        bSaleInfo.Update(item);
                    }
                    /// 同步库存

                    ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.InGoods> bInGoods = new ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.InGoods>();
                    List<ZhiKeDuoServer.Model.InGoods> lsInGoods = bInGoods.GetList("syc=0");
                    foreach (ZhiKeDuoServer.Model.InGoods item in lsInGoods)
                    {
                        string json = JsonConvert.SerializeObject(item);
                        wc.PostJson(api + "add/ingoods/" + mShop.Shop, json);
                        item.syc = 1;
                        bInGoods.Update(item);
                    }
                    /// 同步分类
                    ///
                    ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.Category> bCategory = new ZhiKeDuoServer.BLL.Base<ZhiKeDuoServer.Model.Category>();
                    List<ZhiKeDuoServer.Model.Category> lsCategory = bCategory.GetList("syc=0");
                    foreach (ZhiKeDuoServer.Model.Category item in lsCategory)
                    {
                        string json = JsonConvert.SerializeObject(item);
                        wc.PostJson(api + "add/category/" + mShop.Shop, json);
                        item.syc = 1;
                        bCategory.Update(item);
                    }
                    #endregion
                    #region  下载同步
                    // 同步会员
                    String back = wc.PostJson(api + "/lists/memberinfo/" + mShop.Shop,"");
                    var mblist= JsonConvert.DeserializeObject<List<ZhiKeDuoServer.Model.MemberInfo>>(back);
                    ZhiKeDuoServer.BLL.MemberInfo memberInfob = new ZhiKeDuoServer.BLL.MemberInfo();
                    foreach (var item in mblist)
                    {
                        memberInfob.Add(item);
                        String call = wc.PostJson(api + "/update/memberinfo/" + mShop.Shop+"/"+item.Id, "");
                    }


                    // 同步订单
                     back = wc.PostJson(api + "/lists/saleinfo/" + mShop.Shop, "");
                    var mblistsale = JsonConvert.DeserializeObject<List<ZhiKeDuoServer.Model.SaleInfo>>(back);
                    ZhiKeDuoServer.BLL.SaleInfo saleb = new ZhiKeDuoServer.BLL.SaleInfo();
                    foreach (var item in mblistsale)
                    {
                        saleb.Add(item);
                        String call = wc.PostJson(api + "/update/saleinfo/" + mShop.Shop + "/" + item.Id, "");
                    }

                    // 同步库存
                     back = wc.PostJson(api + "/lists/ingoods/" + mShop.Shop, "");
                    var mInGoodslist = JsonConvert.DeserializeObject<List<ZhiKeDuoServer.Model.InGoods>>(back);
                    ZhiKeDuoServer.BLL.InGoods InGoodsb = new ZhiKeDuoServer.BLL.InGoods();
                    foreach (var item in mInGoodslist)
                    {
                        InGoodsb.Add(item);
                        String call = wc.PostJson(api + "/update/ingoods/" + mShop.Shop + "/" + item.Id, "");
                    }


                    #endregion
                    //var ds_loadMenus = bsaleInfo.GetList("");//

                    //foreach (var item in ds_loadMenus)
                    //{
                    //    _PrintTaskQueue.Enqueue(item.Id);
                    //}


                }
                catch (Exception ex)
                {
                    LogManager.WriteLog("Error", ex.Message);
                }


                //  StartPrintThread();

                Thread.Sleep(1000);
            }
        }

        private void startserver()
        {
            if (_LoadThread == null)
            {
                _LoadThread = new Thread(DetectionPrintRequest);
                _LoadThread.Start();
            }
        }
    }

}
